<route lang="json5" type="page">
{
  style: {
    navigationBarTitleText: '梦瑶诗歌',
    navigationStyle: 'default',
  },
  needLogin: 'true',
}
</route>
<template>
  <wd-toast />
  <view class="page" :style="{ paddingBottom: buttonHeight + 'px' }">
    <view class="poem-card">
      <!-- 诗歌内容卡片（包含诗名、朝代和诗人信息） -->
      <wd-card v-if="showContentCard" title="诗歌内容" :outline="false" title-color="#3a8ee6">
        <view class="poem-content">
          <view class="title-heart-container">
            <!-- 诗名 -->
            <view v-if="poemDetail?.title" class="poem-title">{{ poemDetail.title }}</view>

            <view
              class="i-carbon-favorite-filled heart-icon"
              :class="{ 'text-red': poemDetail.isFavorite === '1' }"
              style="font-size: 48rpx; line-height: 48rpx"
              @click.stop="toggleFavorite"
            ></view>
          </view>

          <!-- 诗人信息 -->
          <view v-if="poemDetail?.author || poemDetail?.dynasty" class="poem-author">
            <text
              v-if="poemDetail.author"
              @click="showAuthorDetail"
              :style="{ color: poemDetail?.authDescription ? 'blue' : 'gray' }"
            >
              {{ poemDetail.author }}
            </text>
            <text v-if="poemDetail.dynasty" style="color: red">〔{{ poemDetail.dynasty }}〕</text>
          </view>

          <!-- 诗歌内容 -->
          <!-- 诗歌内容 -->
          <view v-if="poemDetail?.withPinyin">
            <!-- 遍历每一行 -->
            <view v-for="(line, lineIndex) in groupedPoem" :key="lineIndex" class="poem-line">
              <!-- 用于容纳一行中所有“段”的弹性容器 -->
              <view class="line-segments-container">
                <!-- 遍历一行中的每一个“段”（半句） -->
                <view
                  v-for="(segment, segmentIndex) in line"
                  :key="segmentIndex"
                  class="characters-container"
                >
                  <!-- 遍历一个“段”中的每一个字 -->
                  <view v-for="(item, charIndex) in segment" :key="charIndex" class="char-pair">
                    <view class="pinyin-container">
                      <text class="pinyin">{{ item.pinyin || '　' }}</text>
                    </view>
                    <view class="character-container">
                      <text class="character">{{ item.content }}</text>
                    </view>
                  </view>
                </view>
              </view>
            </view>
          </view>
          <template v-else>
            <!-- 无拼音的情况 -->
            <view
              v-for="(line, index) in groupedPoem"
              :key="index"
              class="poem-line"
              :style="{ fontSize: `${poemFontSize}rpx`, marginBottom: '40rpx' }"
            >
              {{
                line
                  .flat()
                  .map((item) => item.content)
                  .join('')
              }}
            </view>
          </template>
        </view>
      </wd-card>
    </view>

    <view class="poem-card">
      <!-- 翻译卡片 -->
      <wd-card v-if="showTranslationCard" title="翻译" :outline="false" title-color="#3a8ee6">
        <view class="section-content">
          <view
            class="content-text"
            v-html="
              handleTranslateText(
                expandedSections.includes('translation')
                  ? poemDetail?.translation
                  : truncatedTranslation,
              )
            "
            style="white-space: pre-line"
          ></view>
          <wd-button
            v-if="shouldShowExpand('translation')"
            size="small"
            type="text"
            custom-class="expand-btn"
            @click="toggleSection('translation')"
          >
            {{ expandedSections.includes('translation') ? '收起' : '展开' }}
          </wd-button>
        </view>
      </wd-card>
    </view>

    <view class="poem-card">
      <!-- 赏析卡片 -->
      <wd-card v-if="showAppreciationCard" title="赏析" :outline="false" title-color="#3a8ee6">
        <view class="section-content">
          <view class="content-text">
            {{
              expandedSections.includes('appreciation')
                ? poemDetail?.appreciation
                : truncatedAppreciation
            }}
          </view>
          <wd-button
            v-if="shouldShowExpand('appreciation')"
            size="small"
            type="text"
            custom-class="expand-btn"
            @click="toggleSection('appreciation')"
          >
            {{ expandedSections.includes('appreciation') ? '收起' : '展开' }}
          </wd-button>
        </view>
      </wd-card>
    </view>

    <!-- 控制按钮组 -->
    <view class="action-buttons" v-if="showAudioControlButtons">
      <wd-button
        :disabled="!hasAudio"
        type="success"
        size="medium"
        :icon="isPlaying ? 'pause' : 'play'"
        @click="togglePlayPause"
      >
        {{ buttonLabel }}
      </wd-button>
      <wd-button :disabled="!hasAudio" @click="stopPlayback" type="error" icon="stop-circle-filled">
        停止
      </wd-button>
      <wd-button
        :disabled="!hasAudio"
        @click="toggleAutoPlay"
        type="warning"
        :icon="autoPlayNext ? 'pause-circle-filled' : 'play-circle-filled'"
      >
        自动连播
      </wd-button>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { ref, computed, nextTick, onMounted, onUnmounted, getCurrentInstance } from 'vue'
import { favoriteManager } from '@/service/poem/favorite'
import { PoemDetailPageConfig, PoemItemDetail } from '@/api/poem.typings'
import { http } from '@/utils/http'
import { useToast } from 'wot-design-uni'
import { useAuthHeaders } from '@/utils/token'
import { onLoad, onUnload } from '@dcloudio/uni-app'
import { storeToRefs } from 'pinia'
import { BackgroundAudioPlayer } from '@/utils/media/backgroundAudioPlayer'
import { MediaView } from '@/api/children.typing'

const API_BASE_URL = import.meta.env.VITE_API_BASE_URL
const toast = useToast()

const scrollTop = ref<number>(0)
const isLoadingNext = ref(false)
const autoPlayNext = ref(false)
const expandedSections = ref<string[]>([])
const buttonHeight = ref<number>(120)
// 诗歌字体大小
const poemFontSize = ref('')
// 音频播放器
const backgroundAudioPlayer = new BackgroundAudioPlayer(false)
// 设置下一曲回调
backgroundAudioPlayer.setNextTrackCallback(() => {
  console.log('播放结束，自动播放下一曲')
  handleAutoPlayNext()
})
const mediaView = ref<MediaView>()

// 诗歌详情数据
const poemDetail = ref<PoemItemDetail>()
const poemDetailConfig = ref<PoemDetailPageConfig>()
const isLoadingConfig = ref(false)
// 配置诗歌按钮是否显示，仅为了通过微信正式版的审核
const showAudioControlButtons = computed(() => {
  return poemDetailConfig.value?.isShowPlayButton ?? true
})

// 计算属性
const poem = computed(() => poemDetail.value?.content || [])
const isPlaying = computed(() => backgroundAudioPlayer.isPlaying.value)
const hasAudio = computed(() => !!poemDetail.value?.filePath?.trim())
const buttonLabel = computed(() => (backgroundAudioPlayer.isPlaying.value ? '暂停' : '播放'))

// 卡片显示条件计算
const showContentCard = computed(() => {
  return (
    poemDetail.value?.title ||
    poemDetail.value?.author ||
    poemDetail.value?.dynasty ||
    poem.value.length > 0
  )
})
const showTranslationCard = computed(() => {
  return poemDetail.value?.translation && poemDetail.value.translation.trim().length > 0
})
const showAppreciationCard = computed(() => {
  return poemDetail.value?.appreciation && poemDetail.value.appreciation.trim().length > 0
})
const showAuthorCard = computed(() => {
  return poemDetail.value?.authDescription && poemDetail.value.authDescription.trim().length > 0
})

// 截断长度计算
const truncatedLength = 50
const truncatedTranslation = computed(() => {
  const content = poemDetail.value?.translation || ''
  return content.length > truncatedLength ? content.substring(0, truncatedLength) + '...' : content
})
const truncatedAppreciation = computed(() => {
  const content = poemDetail.value?.appreciation || ''
  return content.length > truncatedLength ? content.substring(0, truncatedLength) + '...' : content
})

// 生命周期
onLoad(async (options) => {
  usePageAuth()
  await Promise.all([getPoemDetailPageConfig(), getPoemDetail(options.id)])
})

onUnload(() => {
  backgroundAudioPlayer.stop()
})

// watch(
//   () => poem.value,
//   () => {
//     if (poemDetail.value) {
//       _filePath.value = poemDetail.value.filePath
//     }
//   },
//   {
//     immediate: true, // 确保初始化时执行一次
//   },
// )

onMounted(() => {
  // 在同步钩子内先拿到实例
  const instance = getCurrentInstance()
  // 确保 DOM 渲染完毕
  nextTick(() => {
    const vm = instance!.proxy
    const query = uni.createSelectorQuery().in(vm)
    query
      .select('.action-buttons')
      .boundingClientRect((rect) => {
        if (rect) {
          let r
          if (Array.isArray(rect)) {
            r = rect[0]
          } else {
            r = rect
          }
          // rect.height + 额外间距（60px）+ 安全区底部 inset
          buttonHeight.value = r.height + 60 + getSafeAreaBottom()
        }
      })
      .exec()
  })
})

// 检查是否应显示展开按钮
const shouldShowExpand = (section: string) => {
  if (section === 'translation') {
    return poemDetail.value?.translation && poemDetail.value.translation.length > truncatedLength
  }
  if (section === 'appreciation') {
    return poemDetail.value?.appreciation && poemDetail.value.appreciation.length > truncatedLength
  }
  return false
}

// 切换内容展开状态
const toggleSection = (section: string) => {
  const index = expandedSections.value.indexOf(section)
  if (index > -1) {
    expandedSections.value.splice(index, 1)
  } else {
    expandedSections.value.push(section)
  }
}

// 处理翻译的文本
const handleTranslateText = (translate?: string) => {
  return translate.replace(/↵/g, '<br>')
}

const groupedPoem = computed(() => {
  if (!poemDetail.value?.content) return []

  // 1. 按行索引分组
  const groups: { [key: number]: any[] } = {}
  poemDetail.value.content.forEach((item) => {
    if (!groups[item.lineIndex]) {
      groups[item.lineIndex] = []
    }
    groups[item.lineIndex].push(item)
  })

  // 2. 将分组后的对象转换为数组，并按行索引排序
  const lines = Object.values(groups).sort((a, b) => a[0].lineIndex - b[0].lineIndex)

  // 3. 在每一行内部，根据标点符号分割成“段”（segments）
  const result = lines.map((line) => {
    const segments: any[][] = []
    let currentSegment: any[] = []

    line.forEach((charItem) => {
      currentSegment.push(charItem)
      // 如果遇到逗号或句号，就结束当前段，并开始一个新段
      if (charItem.content === '，' || charItem.content === '。' || charItem.content === '？') {
        segments.push(currentSegment)
        currentSegment = []
      }
    })

    // 将最后剩余的部分（如果存在）也作为一个段添加
    if (currentSegment.length > 0) {
      segments.push(currentSegment)
    }

    return segments
  })

  console.log('new groupedPoem structure', result)
  return result
})

// 获取诗歌详情
const getPoemDetail = async (id: string) => {
  const res = await http.get<PoemItemDetail>(
    `${API_BASE_URL}/api/v1/poetry/${id}`,
    {},
    useAuthHeaders(),
  )
  if (res.code === 200) {
    poemDetail.value = res.data
    const maxLength = Math.max(...poemDetail.value.content.map((s) => s.content.length))
    if (maxLength > 20) {
      poemFontSize.value = '32' // 如果句子很长，统一缩小字体
    } else {
      poemFontSize.value = '36' // 正常字体大小
    }
  } else {
    toast.error(`获取诗歌详情失败，失败信息为：${res.msg}`)
  }
}

const getPoemDetailPageConfig = async () => {
  try {
    isLoadingConfig.value = true
    const res = await http.get<PoemDetailPageConfig>(
      `${API_BASE_URL}/api/v1/global_config/POEM_DETAIL_PAGE`,
      {},
      useAuthHeaders(),
    )
    if (res.code === 200) {
      poemDetailConfig.value = res.data
    } else {
      poemDetailConfig.value = {
        isShowPlayButton: true,
      }
      toast.error(`获取诗歌详情页配置数据失败，失败信息为：${res.msg}`)
    }
  } catch (error) {
    console.error('获取诗歌详情页配置数据失败，失败信息为:', error)
    // 使用默认配置
    poemDetailConfig.value = {
      isShowPlayButton: true,
    }
  } finally {
    isLoadingConfig.value = false
  }
}

const poemConvertMedia = (poem: PoemItemDetail): MediaView => {
  return {
    id: poem.id,
    albumId: poem.id,
    title: poem.title,
    episodeSeq: 1,
    sortOrder: 1,
    filePath: poem.filePath,
    expirationDate: 4091996249000,
    mediaType: 'audio',
  }
}

const togglePlayPause = () => {
  if (!hasAudio.value) {
    uni.showToast({ title: '暂未语音播放文件', icon: 'none' })
    return
  }
  mediaView.value = poemConvertMedia(poemDetail.value)
  backgroundAudioPlayer.toggle(mediaView.value)
}

const stopPlayback = () => {
  backgroundAudioPlayer.stop()
}

const toggleFavorite = () => {
  if (!poemDetail.value) return

  const newState = poemDetail.value.isFavorite === '1' ? '0' : '1'
  const success = favoriteManager.toggleFavorite(poemDetail.value)
  if (success) {
    poemDetail.value.isFavorite = newState
    uni.$emit('updatePoemList', true)
  }
}

const showAuthorDetail = () => {
  if (poemDetail.value?.authDescription) {
    uni.showModal({
      title: `${poemDetail.value.author}简介`,
      content: poemDetail.value.authDescription,
      confirmText: '关闭',
      showCancel: false,
    })
  } else {
    uni.showToast({ title: '暂无作者信息', icon: 'none' })
  }
}

const toggleAutoPlay = () => {
  autoPlayNext.value = !autoPlayNext.value

  toast.show(autoPlayNext.value ? '已开启自动播放' : '已关闭自动播放')
  console.log('isPlaying', backgroundAudioPlayer.isPlaying.value)
  // 如果不是播放状态，自动播放音频
  if (!backgroundAudioPlayer.isPlaying.value && autoPlayNext.value) {
    togglePlayPause()
  }
}

const handleAutoPlayNext = () => {
  if (autoPlayNext.value && !isLoadingNext.value) {
    getRandomNext()
  }
}
// 随机获取相同类型的诗歌
const getRandomNext = async () => {
  if (isLoadingNext.value) {
    toast.error('当前正在切换下一首诗歌中，请耐心等待')
    return
  }

  try {
    isLoadingNext.value = true
    stopPlayback()

    const res = await http.get<PoemItemDetail>(
      `${API_BASE_URL}/api/v1/poetry/random?currentId=${poemDetail.value.id}`,
      {},
      useAuthHeaders(),
    )

    if (res.code === 200) {
      // 直接在赋值时处理数据结构
      poemDetail.value = {
        ...res.data,
      }

      await scrollToTop()

      if (autoPlayNext.value && poemDetail.value.filePath) {
        nextTick(() => {
          togglePlayPause() // 自动播放新诗歌
        })
      }
    }
  } catch (e) {
    console.error('切换失败:', e)
    toast.error('切换失败，请稍后重试')
  } finally {
    isLoadingNext.value = false
  }
}
const scrollToTop = async () => {
  // 先滚动到顶部
  uni.pageScrollTo({
    scrollTop: 0,
    duration: 300,
  })

  // 等待DOM更新
  nextTick(() => {
    // 强制刷新scroll-view（通过设置一个新的随机值）
    scrollTop.value = Math.random()
  })
}
// 获取安全区域高度
const getSafeAreaBottom = () => {
  try {
    const systemInfo = uni.getSystemInfoSync()
    return systemInfo.safeAreaInsets?.bottom || 0
  } catch (e) {
    console.error('获取安全区域失败', e)
    return 0
  }
}
</script>

<style lang="scss" scoped>
.page {
  padding: 20rpx;
  background-color: #f8f8f8;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  box-sizing: border-box;
  font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
  overflow-y: auto;
  height: calc(100vh - env(safe-area-inset-bottom));
}

.poem-card {
  width: 100%;
}

.poem-content {
  text-align: center;
  padding: 24rpx 0;
  line-height: 1.5;
  width: 100%;
  color: #333;
  display: flex;
  flex-direction: column;
  align-items: center;

  .poem-title {
    font-size: 40rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 16rpx;
    line-height: 1.4;
    text-align: center;
  }

  .poem-author {
    font-size: 28rpx;
    color: #666;
    font-style: italic;
    margin-bottom: 24rpx;
    text-align: center;
  }

  .poem-line {
    text-align: center;
    //margin-bottom: 40rpx;
    width: 100%;

    .line-segments-container {
      display: flex;
      align-items: center;
      flex-direction: column;
    }

    .characters-container {
      display: flex;
      justify-content: center;
      flex-wrap: wrap;
    }

    .char-pair {
      display: flex;
      flex-direction: column;
      align-items: center;
      min-width: 1.2em; // 确保每个字有相同的最小宽度
      margin: 0 4rpx; // 字间距
    }

    .pinyin-container {
      height: 36rpx;
      line-height: 36rpx;
    }

    .character-container {
      height: 50rpx;
      line-height: 50rpx;
    }

    .pinyin {
      font-size: 24rpx;
      color: #999;
      text-align: center;
    }

    .character {
      font-size: 36rpx;
      color: #333;
      text-align: center;
    }
  }

  .title-heart-container {
    display: flex;
    align-items: center; /* 垂直居中 */
    justify-content: center; /* 左右分布 */
    position: relative;
    width: 100%; /* 确保宽度填充 */
    margin-bottom: 8px; /* 与下方作者信息保持间距 */
  }
  .heart-icon {
    position: absolute; /* 绝对定位 */
    right: 0; /* 贴紧右侧 */
    top: 50%; /* 垂直居中 */
    transform: translateY(-50%); /* 精确垂直居中 */
    font-size: 48rpx;
    line-height: 1;
    padding: 10rpx; /* 增加点击区域 */
  }
}

.section-content {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center; /* 确保内容居中 */

  .content-text {
    font-size: 36rpx;
    color: #333;
    line-height: 1.8;
    text-align: justify;
    margin-bottom: 20rpx;
    width: 100%;
    word-wrap: break-word;
    white-space: pre-line;
  }

  .expand-btn {
    margin-top: 16rpx;
    color: #3a8ee6;
    font-size: 28rpx;
    text-align: center;
  }
}

.action-buttons {
  position: fixed;
  bottom: 40rpx;
  display: flex;
  justify-content: center;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 100rpx;
  padding: 16rpx;
  box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.1);
  z-index: 100;

  :deep(.wd-button) {
    height: 80rpx;
    margin: 0 10rpx;
    border-radius: 40rpx;
    font-size: 32rpx;
    padding: 0 20rpx;
  }
}
</style>
